import 'dart:convert';

import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/service/user_login_service.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_adapter.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_inherited_widget/vg_inherited_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_stream_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

///用户信息
class UserRepository extends UserAdapter {
  static const String _SP_USER_KEY = "sp_user";

  static UserRepository _instance;

  UserRepository._();

  static UserAdapter getInstance() {
    if (_instance == null) {
      _instance = new UserRepository._();
    }
    return _instance;
  }

  ///登录服务引用 掉内部服务
  UserLoginService _service;

  ///登录相关
  @override
  UserLoginService loginService(
      {VgBaseCallback<UserDataBean> callback, bool isBackIndexPage = true, bool isColdLogin = false}) {
    return _service = UserLoginService(
        VgBaseCallback<UserDataBean>(onSuccess: (UserDataBean userDataBean) {
      if (userDataBean == null ||
          userDataBean.user == null ||
          StringUtils.isEmpty(userDataBean.authId)) {
        if (callback != null && callback.onError != null) {
          callback.onError("信息获取异常～");
        }
        return;
      }
      if (callback != null && callback.onSuccess != null) {
        callback.onSuccess(userDataBean);
      }
      Future(() {
        _loginSuccess(userDataBean, isBackIndexPage, isColdLogin: isColdLogin);
      });
    }, onError: (String msg) {
      if (callback != null && callback.onError != null) {
        callback.onError(msg);
      } else {
        VgToastUtils.toast(AppMain.context, msg);
      }
      _service = null;
    }));
  }

  VgStreamController<UserDataBean> _userStreamController = VgStreamController.hot();

  ///获取用户控制器流
  @override
  Stream<UserDataBean> get userStream => _userStreamController?.stream;

  ///获取用户
  @override
  UserDataBean get userData => _userStreamController?.value;

  ///公司id
  @override
  String get companyId => _userStreamController?.value?.companyId;

  ///获取authId
  @override
  String get authId => _userStreamController?.value?.authId;

  @override
  ///获取最后一次浏览的shid
  String get lastshid => _userStreamController?.value?.lastshid;

  @override
  ///获取终端数量
  int get tercnt => _userStreamController?.value?.tercnt??0;

  @override
  void setLastShid(String shid) {
    if (shid == null) {
      return;
    }
    if (userData == null) {
      return;
    }
    userData.lastshid = shid;
    _setCacheUserInfo(userData);
  }

  @override
  ///是否是智能家居行业应用
  String get trade => _userStreamController?.value?.companyInfo?.trade;

  ///是否是智能家居行业
  ///C144 家居行业 C120物业管理 C115餐饮行业
  @override
  bool isSmartHomeCompany() {
    return "C144" == trade;
  }
  
  ///企业列表
  @override
  List<UserComListBean> get companyList =>
      ((json.decode(json.encode(_userStreamController?.value?.companyList))) as List)
          ?.map((e) => UserComListBean.fromMap(e))
          ?.toList();

  ///通过inherited获取User
  @override
  UserDataBean of(BuildContext context, {bool isListen = true}) {
    return VgInheritedWidget.getData<UserDataBean>(context, listen: isListen);
  }
  
  ///通用完成成功处理回调
  void _loginSuccess(UserDataBean userDataBean, bool isBackIndexPage, {bool isColdLogin}) {
    if (userDataBean == null ||
        userDataBean.user == null ||
        StringUtils.isEmpty(userDataBean.authId)) {
      return;
    }
    _setCacheUserInfo(userDataBean);
    //标注来自冷启动登录，避免首页接口重复请求
    userDataBean.isColdLogin = isColdLogin??false;
    _userStreamController?.add(userDataBean);
    if (isBackIndexPage) {
      RouterUtils.popUntil(AppMain.context, AppMain.ROUTER,
          rootNavigator: false);
    }
    _service = null;
    VgInheritedWidget.updateData<UserDataBean>(
        AppMain.context, userDataBean);
  }

  ///设置缓存用户
  void _setCacheUserInfo(UserDataBean userDataBean) {
    String cache = userDataBean == null ? "" : jsonEncode(userDataBean);
    SharePreferenceUtil.putString(_SP_USER_KEY, cache);
  }

  ///获取用户缓存
  Future<String> _getCacheUserInfo() {
    return SharePreferenceUtil.getString(_SP_USER_KEY);
  }

  ///是否登录
  @override
  bool isLogined() {
    UserDataBean userDataBean = _userStreamController?.value;
    if (StringUtils.isNotEmpty(userDataBean?.authId) && userDataBean?.user != null) {
      return true;
    }
    return false;
  }

  ///清空用户相关和缓存
  ///避免StreamController 处理延迟，添加delayed 100ms 处理等待通知处理完成
  @override
  Future<void> clearUserInfo()  async {
    _setCacheUserInfo(null);
    _userStreamController?.add(null);
    VgInheritedWidget.updateData<UserDataBean>(AppMain.context, null);
    await Future.delayed(Duration(milliseconds: 100),(){
      return Future.value();
    });
  }

  ///直接读取缓存
  @override
  Future<UserDataBean> loadCacheUserInfo() async {
    String userJsonStr = await _getCacheUserInfo();
    if (userJsonStr == null || userJsonStr == "") {
      return null;
    }
    UserDataBean userDataBean = UserDataBean.fromMap(jsonDecode(userJsonStr));
    if (userDataBean == null ||
        userDataBean.user == null ||
        userDataBean.authId == null ||
        userDataBean.authId == "") {
      return null;
    }
    _userStreamController?.add(userDataBean);
    print("----------------------------------------------");
    print("\n");
    print("加载用户信息缓存成功：\n"
        "authId:  ${userDataBean?.authId}\n"
        "************************* \n"
        "companyId:  ${userDataBean?.companyId}\n"
        "************************* \n"
        "companyInfo：${userDataBean?.companyInfo}\n"
        "************************* \n"
        "comUser:  ${userDataBean?.comUser}\n"
        "************************* \n"
        "companyList:  ${userDataBean?.companyList?.toString()}\n"
        "************************* \n"
        "userBean: ${userDataBean?.user}\n"
    );
    print("\n");
    print("----------------------------------------------");
    VgInheritedWidget.updateData<UserDataBean>(
        AppMain.context, userDataBean);
    return Future.value(userDataBean);
  }

  @override
  void dispose() {
    _userStreamController?.close();
    _instance = null;
  }



}
